$(function(){
  layui.use(['element','table','layer','laytpl','form','formSelects'],function(){
    var element = layui.element,
        table = layui.table,
        layer = layui.layer,
        laytpl = layui.laytpl,
        form = layui.form,
        formSelects = layui.formSelects;
    var allAuthList = null, checkData = [];
    //获取权限类别
    authorType();
    //查询全部用户
    getUserData();
    
    function authorType(layero){
       $.ajax({
         type: "GET",
         url: ctx+"/userManger/getAuth.do",
         data: {},
         dataType: "json",
         success: function(data) {
            allAuthList = data;
         }
       });
    }

    function getUserData(){
      $.ajax({
        type: "GET",
        url: ctx+"/userManger/selectAllUser.do",
        data: {},
        dataType: "json",
        success: function(data){
          renderTable(data);
        }
      });
    }
  
    function renderTable(data){
      var tbHeigth = $('.settings-wrap').height();
      table.render({
        elem: '#account-list',
        data: data,
        height: tbHeigth,
        title: '用户信息表',
        toolbar: '#toolbar',
        defaultToolbar: [],
        cols: [[ //展示的列
          {type: 'radio', fixed: 'left'},
          {field:'loginName', title: '用户名'},
          {field:'phoneNo', title: '电话'},
          {field:'auths', title: '权限'}
        ]],
        page: {
          layout: ['prev', 'page', 'next', 'count','skip','limit']
          , groups: 5 //只显示 5 个连续页码
          , limit: 15  //每页显示条数
          , limits: [15, 30, 45, 60]
        },
        loading: true,
        done: function(){
          $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
          $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
        }
      });
    }

    //头工具栏事件
    table.on('toolbar(account-list)', function(obj){
      var checkStatus = table.checkStatus(obj.config.id); //获取选中行状态
      switch(obj.event){
        case 'getCheckData':
          checkData = checkStatus.data;  //获取选中行数据
          // console.log(checkData);
          break;
      };
    });

    // 新增
    $('.addBtn').click(function () {
      var layerIdx = layer.open({
        type: 1,
        title: "新增",
        closeBtn: 1,
        anim: 0,
        area: 'auto',
        content: $('#add-tpl').html(),
        success: function (layero, index) {
          form.val("rowEditForm", checkData[0]);
          var getTpl = $('#auth-tpl').html();
          laytpl(getTpl).render(allAuthList, function(html){
            layero.find('.authority').html(html);
            formSelects.render('select-auth');
            formSelects.btns('select-auth', []);
          });
        }
      });
      form.on('submit(add-param)', function (res) {
        // console.log(res.field); //当前容器的全部表单字段，名值对形式：{name: value}
        addUsers(res.field);
        layer.close(layerIdx);
        return false;
      });
      $(".add-param button[type='cancel']").click(function () {
        layer.close(layerIdx);
        return false;
      });
    });

    // 编辑
    $('.editBtn').click(function(){
      $('.getCheckData').click();
      if(checkData.length === 1){
        var layerIdx = layer.open({
          type: 1,
          title: "编辑",
          closeBtn: 1,
          anim: 0,
          area: 'auto',
          content: $('#edit-tpl').html(),
          success: function (layero, index) {
            form.val("edit-param", checkData[0]);
            var getTpl = $('#auth-tpl').html();
            laytpl(getTpl).render(allAuthList, function(html){
              layero.find('.authority').html(html);
              formSelects.render('select-auth');
              formSelects.btns('select-auth', []);
              var this_auth = checkData[0].auths.split(',');
              var this_authcode = [];
              for (var i = 0; i < allAuthList.length; i++) {
                for (var j = 0; j < this_auth.length ; j++) {
                  if(allAuthList[i].authName == this_auth[j]){
                    this_authcode.push(allAuthList[i].authCode)
                  }
                }
              }
              formSelects.value('select-auth', this_authcode ,true);
            });
          }
        });
        form.on('submit(edit-param)', function(res){
          // console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
          updateUsers(res.field);
          layer.close(layerIdx);
          return false;
        });
        $(".edit-param button[type='cancel']").click(function(){
          layer.close(layerIdx);
          return false;
        });
      }else{
        layer.alert('请选择一条数据')
      }
    });

    // 删除
    $('.delBtn').click(function () {
      $('.getCheckData').click();
      if (checkData.length === 1) {
        var layerIdx = layer.confirm('确认删除?', function (index) {
          // console.log(checkData[0]);
          deleteUsers(checkData[0]);
          layer.close(index);
        });
      } else {
        layer.alert('请选择一条数据')
      }
    });

    function addUsers(data){
      $.ajax({
        type: "POST",
        url: ctx+"/userManger/insert.do",
        data: data,
        dataType: "json",
        success: function(result){
          if(result.code == '000000'){
            getUserData();
          }else{
            layer.msg(result.message);
          }
        }
      });
    }

    function updateUsers(data){
      $.ajax({
        type: "POST",
        url: ctx+"/userManger/editUser.do",
        data: data,
        dataType: "json",
        success: function(result){
          getUserData();
          // obj.update(data); //更新table对应值
        }
      });
    }

    //删
    function deleteUsers(data) {
      $.ajax({
        type: "POST",
        url: ctx + "/userManger/deleteUser.do",
        data: data,
        dataType: "json",
        success: function (result) {
          if (result.code == '000000') {
            getUserData();
          }
        }
      });
    }


  });
});


